import yaml
import os
import sys
import pywifi

from time import sleep, time
import ping3

from authv3 import CQUPTDrcom

# print(os.path.abspath(sys.argv[0]))

config_path = './config.yaml'
if os.path.isfile(config_path):
    with open(config_path) as y:
        config = yaml.load(y.read(), Loader=yaml.FullLoader)
else:
    config = {
        'user': None,
        'password': None,
        'ip': None,
        'method': 'cmcc',
        'phone': False
    }
    with open(config_path, 'w') as y:
        yaml.dump(config, y, sort_keys=False)
    print('请先按照生成的config.yaml更改设置后, 再使用本脚本.')
    print(f'''
    user:       你的\033[1;33;40m用户名\033[0m.
    password:   你的\033[1;33;40m密码\033[0m.
    ip:         电脑直接连接到校园网的时候, 可以不填;
                如果是作为脚本挂在路由器上的, 也可以不填;
                只有客户端跨过路由器连接到校园网时, 才需要手动在此处填写\033[1;33;40m路由器的ip\033[0m.
    method:     电信对应\033[1;33;40mtelecom\033[0m, 移动对应\033[1;33;40mcmcc\033[0m, 教师或临时对应\033[1;33;40mxyw\033[0m.
    phone:      模拟手机连接时请填写\033[1;33;40mtrue\033[0m, 模拟电脑连接时填写\033[1;33;40mfalse\033[0m.
    ''')
    sys.exit(0)

if config['user'] == None or config['password'] == None:
    print('账号和密码都不能为空!')
    sys.exit(0)

if config['method'] not in ('cmcc', 'telecom', 'xyw'):
    print('账号类型不正确!')
    sys.exit(0)

lag2 = ping3.ping('www.baidu.com')
if isinstance(lag2, float):
    print(f' - [{int(time())}]网络正常, 无需登录.')
    sys.exit(0)
else:
    print(f' - [{int(time())}]开始登陆流程.')

in_school = False
lag1 = ping3.ping('192.168.200.2')
if isinstance(lag1, float):
    print(f' - [{int(time())}]当前处在校园网内.')
    in_school = True
else:
    print(f' - [{int(time())}]当前不在校园网内, 正在尝试搜索CQUPT系列WiFi.')
    wifi = pywifi.PyWiFi()
    ifaces = wifi.interfaces()
    if len(ifaces) == 0:
        print(f' - [{int(time())}]您没有无线网卡！请自行配置有线网络环境后重启本应用！')
    else:
        iface = ifaces[0]
        print(f' - [{int(time())}]使用默认的无线网卡 {iface.name()}')
        iface.scan()
        sleep(5)
        iface.scan()
        sleep(5)
        result = iface.scan_results()
        target = [i for i in result if 'CQUPT' in i.ssid]
        print(f' - [{int(time())}]共找到{len(target)}个WiFi.')

        for i in range(len(target)):
            _t = target[i]
            print(f' - 正在尝试连接第 {i+1} / {len(target)} 个WiFi {_t.ssid}')
            iface.connect(_t)
            sleep(5)
            lag1 = ping3.ping('192.168.200.2')
            if isinstance(lag1, float):
                print(f' - [{int(time())}]当前处在校园网内.')
                in_school = True
                break
            else:
                print(f' - [{int(time())}]当前不在校园网内, 继续连接下一个WiFi.')
        if not in_school:
            print(f' - [{int(time())}]所有WiFi均无法连通到校园网!')
            raise BaseException

if not in_school:
    print(f' - [{int(time())}]无法连接到校园网!')
    raise BaseException

conn = CQUPTDrcom(name=config['user'], pw=config['password'], ip=config['ip'], method=config['method'], phone=config['phone'])
# conn.detect_ip()

lag2 = ping3.ping('www.baidu.com')
if isinstance(lag2, float):
    print(f' - [{int(time())}]网络正常, 无需登录.')
else:
    result = conn.login()
    if result != 0:
        print(f' - [{int(time())}]登陆异常.')
        print(f' - [{int(time())}]目前已知会造成这类问题的原因有: 重复登陆, 账号占用.')
    else:
        print(f' - [{int(time())}]登陆成功.')
    # break
    # sleep(60)